package com.ruoyi.wetest.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * @author Allen
 * @description TODO
 * @Date 2024/4/30 20:35
 */

public class IdGeneratorSnowflake {
    private static IdGeneratorSnowflake instance;
    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake;

    // 私有构造方法，防止外部实例化
    private IdGeneratorSnowflake() {
        // 使用工作ID和数据中心ID创建雪花算法对象
        this.snowflake = IdUtil.createSnowflake(workerId, datacenterId);
    }

    // 获取单例实例的方法
    public static synchronized IdGeneratorSnowflake getInstance() {
        if (instance == null) {
            instance = new IdGeneratorSnowflake();
        }
        return instance;
    }

    // 获取下一个雪花ID
    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    // 根据指定的workerId和datacenterId获取雪花ID
    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
}
